package org.xurui.sxl.protocol;

import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.Opt;
import org.jetlinks.core.ProtocolSupport;
import org.jetlinks.core.defaults.CompositeProtocolSupport;
import org.jetlinks.core.device.DeviceRegistry;
import org.jetlinks.core.message.codec.DefaultTransport;
import org.jetlinks.core.message.interceptor.DeviceMessageSenderInterceptor;
import org.jetlinks.core.metadata.DefaultConfigMetadata;
import org.jetlinks.core.metadata.DeviceConfigScope;
import org.jetlinks.core.metadata.types.IntType;
import org.jetlinks.core.metadata.types.StringType;
import org.jetlinks.core.spi.ProtocolSupportProvider;
import org.jetlinks.core.spi.ServiceContext;
import org.jetlinks.supports.official.JetLinksDeviceMetadataCodec;
import org.xurui.sxl.protocol.codec.TcpMessageCodec;
import org.xurui.sxl.protocol.interceptor.MyDeviceMessageSenderInterceptor;
import reactor.core.publisher.Mono;

import java.util.Optional;

/**
 * 上学啦设备消息协议
 */
@Slf4j
public class SxlProtocolSupportProvider implements ProtocolSupportProvider {

    private static final DefaultConfigMetadata sxlConfig = new DefaultConfigMetadata(
        "学生卡配置"
        , "")
        .add("zzs", "制造商名称", "上学啦 HQ,TJ,TC,TL,TD,TE,TM,TS,TP 其他厂商 ZL,TN,LX,TY,LS", StringType.GLOBAL, DeviceConfigScope.product,DeviceConfigScope.device);//只需要产品配置
    @Override
    public Mono<? extends ProtocolSupport> create(ServiceContext context) {
        if (log.isDebugEnabled()) {
            log.debug("初始化上学啦设备消息协议");
        }
        CompositeProtocolSupport support = new CompositeProtocolSupport();
        // 协议ID
        support.setId("sxl-v0");
        // 协议名称
        support.setName("上学啦设备协议-v0");
        // 协议说明
        support.setDescription("上学啦设备协议");
        // 物模型编解码，固定为JetLinksDeviceMetadataCodec
        support.setMetadataCodec(new JetLinksDeviceMetadataCodec());
        Optional<DeviceRegistry> registry = context.getService(DeviceRegistry.class);
        MyDeviceMessageSenderInterceptor senderInterceptor = new MyDeviceMessageSenderInterceptor();
        support.addMessageSenderInterceptor(senderInterceptor);

        //上线补发离线消息
//        support.
//        support.doOnDeviceRegister(deviceOperator->{
//            senderInterceptor.sendWillDeviceMsg(deviceOperator);
//            return Mono.empty();
//        });


        //TCP消息编解码器
        TcpMessageCodec codec = new TcpMessageCodec(context,senderInterceptor,registry);
        // 两个参数，协议支持和编解码类DemoDeviceMessageCodec中保持一致，第二个参数定义使用的编码解码类
        support.addMessageCodecSupport(DefaultTransport.TCP, () -> Mono.just(codec));
        support.addConfigMetadata(DefaultTransport.TCP,()->Mono.just(sxlConfig));
        return Mono.just(support);
    }
}
